﻿using P2P.Main.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P2P.Util
{
    public class PacketInfo
    {
        public int Identifier { get; set; }
        public int SequenceNumber { get; set; }
        public string PacketText { get; set; }
        public bool IsEnableAES { get; set; }
        public string AesKey { get; set; }
    }

    public class BuildPacketUtil
    {
        public static byte[] PacketBuilder(PacketInfo packetInfo) 
        {
            byte[] packetBuffer;
            if (packetInfo.IsEnableAES)
            {
                packetBuffer = AESUtil.Encrypt(Encoding.UTF8.GetBytes(packetInfo.PacketText), packetInfo.AesKey);
            }
            else
            {
                packetBuffer = Encoding.UTF8.GetBytes(packetInfo.PacketText);
            }

            byte[] bytes = new byte[packetBuffer.Length + 8];
            Buffer.BlockCopy(BitConverter.GetBytes(packetInfo.Identifier), 0, bytes, 0, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(packetInfo.SequenceNumber), 0, bytes, 4, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(packetBuffer.Length), 0, bytes, 8, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(packetInfo.IsEnableAES), 0, bytes, 12, 1);
            Buffer.BlockCopy(packetBuffer, 0, bytes, 13, packetBuffer.Length);

            return bytes;
        }
    }
}
